# 
# @Author: Cjuicy 
# @Date: 2022-03-21 16:00:23 
# @Last Modified by:   Cjuicys 
# @Last Modified time: 2022-03-21 16:00:23 
# 


from asyncio.windows_events import NULL
from asyncore import write
from cProfile import label
from pickle import TRUE
import sys
from unittest import result
import cv2
import time
import argparse
import random
import torch
import numpy as np
import pandas as pd
import torch.backends.cudnn as cudnn


from utils.torch_utils import select_device
from models.experimental import attempt_load
from utils.general import check_img_size, non_max_suppression, scale_coords
from utils.datasets import letterbox
from utils.plots import plot_one_box2
from utils.torch_utils import select_device, load_classifier, time_synchronized

'''导入qt库'''
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

import csv


'''导入自己的文件'''
from ui.food_ui import Ui_MainWindow
from utils import food_info_utils #,food_sql


class Ui_Logic_Window(QtWidgets.QWidget):
    def __init__(self,parent=None):
        super().__init__(parent)                            #父类的构造函数
        self.cap = cv2.VideoCapture()                       #视频流
        self.timer_video = QtCore.QTimer()                  #定义定时器，用于控制显示视频的帧率
        
        '''csv表格操作'''
        self.price_info,self.names_info = food_info_utils.get_price_info()      # 获取表格价钱信息
        
        '''GUI部分'''
        self.ui = Ui_MainWindow()
        # self.setWindowTitle("慧结算")                       #设置窗口标题名
        
        self.layout_main = self.ui.set_ui()                      #初始化页面布局
        self.layout_main.setWindowIcon(QIcon("./ui/icon/hjs.png"))        #设置icon 不知道为啥在food_ui这个图标就上不去
        
        arr,row = food_info_utils.get_food_info()                   #获取tab2表格数据
        self.ui.refresh_row(arr,row)                            #更新tab2表格数据
        
        # layout_main.show()

        # self.setLayout(layout_main)                         #到这步才会显示所有控件
        self.slot_init()                                    #初始化槽函数
        self.ui.button_settle_accounts.setDisabled(True)    #将结账按钮触发禁用


        '''先定义一些变量'''
        self.num_stop = 1                                   # 暂停与播放辅助信号，note：通过奇偶来控制暂停与播放
        self.output_folder = 'output/'
        self.vid_writer = None
        self.order_info = ''                                #用于存储订单的信息
        self.arr = np.array(arr)                                       #用于存放最新的food_info.csv表的信息

        '''初始化模型'''
        self.openfile_name_model = "./yolov5s.pt"
        self.model_init()

        self.button_camera_open()                           # 打开摄像头检测
        # self.button_video_open()


    
 
    '''槽函数，用于一些触发事件'''
    def slot_init(self):
        
        self.ui.button_confirm.clicked.connect(self.button_video_stop)    
        self.ui.button_settle_accounts.clicked.connect(self.insert_order)
        self.timer_video.timeout.connect(self.show_video_frame) 
        self.ui.button_picture.clicked.connect(self.button_image_open)
        self.ui.add_confirm_button_tab2.clicked.connect(self.button_add_confirm_tab2)
        self.ui.delete_confirm_button_tab2.clicked.connect(self.button_delete_confirm_tab2)
        self.ui.alter_confirm_button_tab2.clicked.connect(self.button_alter_confirm_tab2)
        self.ui.select_confirm_button_tab2.clicked.connect(self.button_select_confirm_tab2)

    

    '''加载相关参数，并初始化模型'''
    def model_init(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
        parser.add_argument('--source', type=str, default='data/images', help='source')  # file/folder, 0 for webcam
        parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
        parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
        parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
        parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
        parser.add_argument('--view-img', action='store_true', help='display results')
        parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
        parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
        parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
        parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
        parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
        parser.add_argument('--augment', action='store_true', help='augmented inference')
        parser.add_argument('--update', action='store_true', help='update all models')
        parser.add_argument('--project', default='runs/detect', help='save results to project/name')
        parser.add_argument('--name', default='exp', help='save results to project/name')
        parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
        self.opt = parser.parse_args()
        # print(self.opt)
        source, weights, view_img, save_txt, imgsz = self.opt.source, self.opt.weights, self.opt.view_img, self.opt.save_txt, self.opt.img_size

        if self.openfile_name_model:
            weights = self.openfile_name_model
            print("Using button choose model")

        # self.device = select_device(self.opt.device)
        self.device = torch.device('cuda:0')
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA

        cudnn.benchmark = True

        # Load model
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=stride)  # check img_size
        if self.half:
            self.model.half()  # to FP16
        #  Second-stage classifier
        classify = False
        if classify:
            modelc = load_classifier(name='resnet101', n=2)  # initialize
            modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=self.device)['model']).to(self.device).eval()

        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]
        # print("model initial done")
        
        # 设置提示框
        # QtWidgets.QMessageBox.information(self, u"Notice", u"模型加载完成", buttons=QtWidgets.QMessageBox.Ok,
                                    #   defaultButton=QtWidgets.QMessageBox.Ok)




    # 目标检测
    def detect(self, name_list, img):
        '''
        :param name_list: 文件名列表
        :param img: 待检测图片
        :return: info_show:检测输出的文字信息
        '''
        showimg = img
        with torch.no_grad():
            img = letterbox(img, new_shape=self.opt.img_size)[0]
            # Convert
            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = np.ascontiguousarray(img)
            img = torch.from_numpy(img).to(self.device)
            img = img.half() if self.half else img.float()  # uint8 to fp16/32
            img /= 255.0  # 0 - 255 to 0.0 - 1.0
            if img.ndimension() == 3:
                img = img.unsqueeze(0)
            # Inference
            pred = self.model(img, augment=self.opt.augment)[0]
            # Apply NMS
            pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes,
                                       agnostic=self.opt.agnostic_nms)
            info_show = ""

            # --定义标签变量名--
            label_names = ""

            # Process detections
            for i, det in enumerate(pred):
                if det is not None and len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], showimg.shape).round()
                    for *xyxy, conf, cls in reversed(det):
                        
                        # if self.names[int(cls)] in self.names_info:                         #将英文替换为中文
                        #     chinese_name = str(self.names_info[self.names[int(cls)]])         #
                            
                        # label = '%s %.2f' % (self.names[int(cls)], conf)                  #原始代码
                        label = '%s %.2f' % (self.names[int(cls)], conf)                    #这是英文
                        # ch_text = '%s %.2f' % (chinese_name, conf)                          #这是中文label 传入plot_one_box2就好 


                        name_list.append(self.names[int(cls)])
                        single_info = plot_one_box2(xyxy, showimg, label=label, color=self.colors[int(cls)], line_thickness=2)
                        # print(single_info)
                        info_show = info_show + single_info + "\n"

                        #获取检测到的所有标签
                        label_names = label_names+","+self.names[int(cls)]
                
            label_names = label_names.split(",")                                # 转化为数组(字符串头有一个',')
            label_names = [i for i in label_names if(len(str(i))!=0)]           # 去掉数组内的空值

        return  info_show , label_names

    '''设置保存的视频名字和路径'''
    def set_video_name_and_path(self):
        now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
        # if vid_cap:  # video
        fps = self.cap.get(cv2.CAP_PROP_FPS)
        w = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        h = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        save_path = self.output_folder + 'video_output/' + now + '.mp4'
        return fps, w, h, save_path


    '''打开摄像头检测'''
    def button_camera_open(self):
        print("Open camera to detect")
        camera_num = 0
        self.cap = cv2.VideoCapture(camera_num)
        bool_open =self.cap.open(camera_num)
        if not bool_open:
            QtWidgets.QMessageBox.warning(self, u"Warning", u"打开摄像头失败", buttons=QtWidgets.QMessageBox.Ok,
                                          defaultButton=QtWidgets.QMessageBox.Ok)
        else:
            fps, w, h, save_path = self.set_video_name_and_path()
            # fps = 5 # 控制摄像头检测下的fps，Note：保存的视频，播放速度有点快，我只是粗暴的调整了FPS
            self.vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
            self.timer_video.start(30)

    '''定义视频帧操作'''
    def show_video_frame(self):
        name_list = []
        flag, img = self.cap.read()
        if img is not None:
            info_show , label_names = self.detect(name_list, img)   # 检测结果写入到原始img上
            self.vid_writer.write(img)                              # 检测结果写入视频
            # print(info_show)

            self.set_labels(label_names)                            # 处理lable并显示在GUI上
            
            

            show = cv2.resize(img, (640, 480))                      # 直接将原始img上的检测结果进行显示
            self.result = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
            showImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0],
                                     QtGui.QImage.Format_RGB888)
            # self.ui.label.setPixmap(QtGui.QPixmap.fromImage(showImage))
            self.ui.label_show_camera_tab.setPixmap(QtGui.QPixmap.fromImage(showImage))  #往显示视频的Label里 显示QImage
            # self.ui.label.setScaledContents(True)  # 设置图像自适应界面大小

        else:
            self.timer_video.stop()         # 读写结束，释放资源
            self.cap.release()              # 释放video_capture资源
            self.vid_writer.release()       # 释放video_writer资源
            

            self.ui.button_settle_accounts.setDisabled(True)    # 视频帧显示期间，禁用结账按键功能


    ''' 暂停与继续检测 '''
    def button_video_stop(self):
        self.timer_video.blockSignals(False)
        # 暂停检测
        # 若QTimer已经触发，且激活
        if self.timer_video.isActive() == True and self.num_stop%2 == 1:
            self.ui.button_confirm.setText(u'重新确认')           #当前状态为暂停状态
            self.num_stop = self.num_stop + 1                   # 调整标记信号为偶数

            self.timer_video.blockSignals(True)
            
            self.ui.button_settle_accounts.setDisabled(False)   # 启动结账按钮
        # 继续检测
        else :
            self.num_stop = self.num_stop + 1
            self.ui.button_confirm.setText(u'确认')
            self.ui.button_settle_accounts.setDisabled(True)
        
        


     # 打开图片并检测
    def button_image_open(self):
        self.button_video_stop()                                #将摄像头暂停
        print('button_image_open')
        name_list = []
        try:
            img_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "打开图片", "data/images", "*.jpg;;*.png;;All Files(*)")
        except OSError as reason:
            print('文件打开出错啦！核对路径是否正确'+ str(reason))
        else:
            # 判断图片是否为空
            if not img_name:
                QtWidgets.QMessageBox.warning(self, u"Warning", u"打开图片失败", buttons=QtWidgets.QMessageBox.Ok,
                                              defaultButton=QtWidgets.QMessageBox.Ok)
                self.button_video_stop()    
            else:
                # self.num_stop = self.num_stop + 1                       #摄像头暂停修正，否则两次图像识别，第二次无法读取图片，这也会导致另一个按钮得点两次（是个大问题）
                img = cv2.imread(img_name)
                print("img_name:", img_name)
                info_show , label_names = self.detect(name_list, img)
                
                # 获取当前系统时间，作为img文件名
                now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
                file_extension = img_name.split('.')[-1]
                new_filename = now + '.' + file_extension # 获得文件后缀名
                file_path = self.output_folder + 'img_output/' + new_filename
                cv2.imwrite(file_path, img)
                
                # 检测信息显示在界面
                self.set_labels(label_names)                            # 处理lable并显示在GUI上
                # self.ui.textBrowser.setText(info_show)

                # 检测结果显示在界面
                self.result = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
                self.result = cv2.resize(self.result, (640, 480), interpolation=cv2.INTER_AREA)
                self.ShowImage = QtGui.QImage(self.result.data, self.result.shape[1], self.result.shape[0], QtGui.QImage.Format_RGB32)
                self.ui.label_show_camera_tab.setPixmap(QtGui.QPixmap.fromImage(self.ShowImage))
                self.ui.label_show_camera_tab.setScaledContents(True)
                
                # self.ui.label.setScaledContents(True) # 设置图像自适应界面大小

    '''处理获取到的lable函数'''
    def set_labels(self ,labels ):
        self.ui.list_show.clearContents()                                               #对表格先进行一个清空
        labels = pd.value_counts(labels)                                                #对标签数组进行重复个数统计

        total_price = 0
        order_sql = []    
        
        if len(labels.index.values) != 0:
            labels_sum = len(labels.index.values)                                       #获取标签总数
            for i in range(labels_sum):
                label_num = str(labels.values[i])                                       #获取对应标签的个数

                if labels.index.values[i] in self.names_info:                           #将英文替换为中文
                    label_name = str(self.names_info[labels.index.values[i]])
                    self.ui.list_show.setItem(i,0,QTableWidgetItem(label_name))         #添加对应标签名字
                else:
                    self.ui.list_show.setItem(i,0,QTableWidgetItem(labels.index.values[i])) #添加没有匹配到中文的名字
               
                
                self.ui.list_show.setItem(i,1,QTableWidgetItem(label_num))              #添加对应标签个数
                #记录数据库要插入的字符 
                order_sql.append(str(labels.index.values[i]))
                order_sql.append(str(label_num))     

                # 判断字典内是否有该key,有添加对应价钱数据，没有则选择默认值（99元）
                if labels.index.values[i] in self.price_info :
                    label_price = str(self.price_info[labels.index.values[i]])
                    self.ui.list_show.setItem(i,2,QTableWidgetItem("¥"+label_price))
                    # 计算总价
                    total_price = total_price + (float(label_price) * int(label_num))
                else :
                    self.ui.list_show.setItem(i,2,QTableWidgetItem("99"))
                    # 计算总价
                    total_price = total_price + (float(99) * int(label_num))



                #设置数据库内容
                if i+1>=labels_sum:                         #判断是不是遍历到了标签最后
                   while(i<5):                              #循环，添加剩余的例如数据库的内容
                       order_sql.append('null')
                       order_sql.append('null')
                       i = i+1


        account = "总价：¥ "+ str(total_price)
        self.ui.label_account.setText(account)

        #设置数据库
        order_sql.insert(0,str(total_price))                #插入总价钱
        order_sql.insert(0,"null")                          #插入id变量
        order_sql.append("CURRENT_TIMESTAMP")               #插入当前时间
        
        # print(order_sql)
        self.order_info = order_sql

    '''插入数据'''
    def insert_order(self):
        price = self.order_info[1]              #获取价钱
        if price == '0':
            QtWidgets.QMessageBox.information(self, u"Notice", u"抱歉,没有识别到食物", buttons=QtWidgets.QMessageBox.Ok,defaultButton=QtWidgets.QMessageBox.Ok)
            self.button_video_stop()
        else:
            # 设置提示框
            click = QtWidgets.QMessageBox.information(self, u"Notice", u"您确定结账吗", 
            QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No)
            if(click == QMessageBox.Yes):
                with open("./food_csv.csv", "a+",newline='') as csvfile:
                    writer = csv.writer(csvfile)
                    writer.writerow(self.order_info)
                    csvfile.close()
                    QtWidgets.QMessageBox.information(self, u"Notice", u"结账成功", buttons=QtWidgets.QMessageBox.Ok,defaultButton=QtWidgets.QMessageBox.Ok)
                    self.button_video_stop()
            else:
                self.button_video_stop()
        
        # food_sql.insert_order_info(self.order_info)
        #  显示数据
        # food_sql.select_order_info()

     # 打开视频并检测
    def button_video_open(self):
        # video_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, "打开视频", "data/", "*.mp4;;*.avi;;All Files(*)")
        flag = self.cap.open('C:/Users/24265/Desktop/3.mp4')
        if not flag:
            QtWidgets.QMessageBox.warning(self, u"Warning", u"打开视频失败", buttons=QtWidgets.QMessageBox.Ok,defaultButton=QtWidgets.QMessageBox.Ok)
        else:
            #-------------------------写入视频----------------------------------#
            fps, w, h, save_path = self.set_video_name_and_path()
            self.vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))

            self.timer_video.start(30) # 以30ms为间隔，启动或重启定时器
            # 进行视频识别时，关闭其他按键点击功能
            # self.ui.pushButton_video.setDisabled(True)
            # self.ui.pushButton_img.setDisabled(True)
            # self.ui.pushButton_camer.setDisabled(True)

    #按钮查询功能
    def button_select_confirm_tab2(self):
        str1 = self.ui.select_LineEdit_tab2.text()
        if len(str1) ==0:                                   #判断字符是否为空
            self.ui.select_lable.setText("请输入数据")
            return 0

        if str1.find("_") == -1:                            #检测出是中文
            for i in range(self.arr.shape[0]):
                if  str1 == self.arr[i][2]:
                    self.ui.select_lable.setText( "行号："+str(i+1)+" 拼音："+self.arr[i][0]+" 价格：¥"+self.arr[i][1]+" 中文："+self.arr[i][2])
                    break
                else:
                    self.ui.select_lable.setText("抱歉没有找到该菜品")
        else:                                               #为拼音
            for i in range(self.arr.shape[0]):
                if  str1 == self.arr[i][0]:
                    self.ui.select_lable.setText( "行号："+str(i+1)+" 拼音："+self.arr[i][0]+" 价格：¥"+self.arr[i][1]+" 中文："+self.arr[i][2])
                    break
                else:
                    self.ui.select_lable.setText("抱歉没有找到该菜品")
        return 0 
    
    #检查是否为中文字符
    def check_contain_chinese(self,check_str):
        for ch in check_str:
            if u'\u4e00' <= ch <= u'\u9fff':
                return True     
            else:
                return False

    #查询按钮重构——查询的表是food_info表
    def select_list_tab2(self,str2):
        flag = -1
        str1 = str(str2)
        str1 = str1.replace("_",'')                                #将短横线去除
        str1 = str1.replace(" ",'')
        print(str1)

        #flag 为空：0
        if len(str1) == 0:                                   #判断字符是否为空
            flag = 0                                        #为空返回零
            return flag

        #flag 拼音重复：1 为拼音：2
        if str1.encode('UTF-8').isalpha():                                 #如果为拼音
            for i in range(self.arr.shape[0]):
                if  str2 == self.arr[i][0]:                 #str2是没有去掉_的拼音
                    flag = 1                                #拼音重复
                    return flag
            
            flag = 2                                #为拼音
            return flag
        #flag 为数字：3
        if str1.isdigit():
            flag = 3                                        #为数字
            return flag

        #为重复中文：3 为中文：5
        if self.check_contain_chinese(str1):
            for i in range(self.arr.shape[0]):
                if  str1 == self.arr[i][2]:
                    flag = 4                                #重复中文返回4
                    return flag
            flag = 5                                #为中文
            return flag

        return flag   

    def button_add_confirm_tab2(self):
        str1 = self.ui.add_LineEdit_tab2_1.text()                                       #获取输入框内的数据
        str2 = self.ui.add_LineEdit_tab2_2.text()
        str3 = self.ui.add_LineEdit_tab2_3.text()

        select_result_1 = self.select_list_tab2(str1)                                   #返回结果 检查拼音
        select_result_2 = self.select_list_tab2(str2)
        select_result_3 = self.select_list_tab2(str3)                                   #检查 中文
        print(select_result_1,select_result_2,select_result_3)


        if len(str1) == 0 or len(str2)== 0 or len(str3)==0:                            #判断字符是否为空
            self.ui.add_hint_lable.setText("请将数据填写在输入框中")
            return 0
        elif select_result_1 ==  1:
            self.ui.add_hint_lable.setText("已存在该拼音")
            return 0
        elif select_result_1 != 2:
            self.ui.add_hint_lable.setText("请输入拼音")
            return 0
        elif select_result_2 != 3:
            self.ui.add_hint_lable.setText("在第二个输入框内请填入数字")
            return 0 
        elif select_result_3 == 4:
            self.ui.add_hint_lable.setText("已存在中文")
            return 0
        elif select_result_3 !=5:
            self.ui.add_hint_lable.setText("请输入中文")
            return 0
        else:
            arr = np.array([str1,str2,str3])                                        #数组追加内容到最后
            self.arr = np.r_[self.arr,[arr]]        
            food_info_utils.add_arr_food_info_csv(arr)                              #将添加的内容添加到csv表格内
            self.ui.refresh_row(self.arr,self.arr.shape[0])
            self.ui.add_hint_lable.setText("添加成功")
            self.price_info,self.names_info = food_info_utils.get_price_info()      # 更新信息，让检测时，信息即使改变     
        return 0 

    def button_delete_confirm_tab2(self):
        str1 = self.ui.delete_LineEdit_tab2_1.text()
        if str1.isdigit() == False:
            self.ui.delete_hint_lable.setText("请输数字")
            return 0

        num = int(str1)
        if num > 0 and num<=len(self.arr):
            self.arr = np.delete(self.arr,num-1,0)
            print(self.arr)
            food_info_utils.delete_arr_food_info_csv(num-1) #这些数据编号都是从0开始，所以需要减1
            arr,row = food_info_utils.get_food_info()                   #获取tab2表格数据
            self.ui.refresh_row(arr,row)                                #表格刷新
            self.arr = np.array(arr)                                    #更新存放在内存的数组
            self.ui.delete_hint_lable.setText("删除成功")
            self.price_info,self.names_info = food_info_utils.get_price_info()      # 更新信息，让检测时，信息即使改变
        else:
            self.ui.delete_hint_lable.setText("请输入准确行号")


        return 0 

    def button_alter_confirm_tab2(self):
        str1 = self.ui.alter_LineEdit_tab2_1.text()
        str2 = self.ui.alter_LineEdit_tab2_2.text()
        str3 = self.ui.alter_LineEdit_tab2_3.text()
        str4 = self.ui.alter_LineEdit_tab2_4.text()

        if len(str1) != 0:                                                          #不为空
            if str1.isdigit():                                                      #如果为数字
                num = int(str1)
                if num>0 and num<=len(self.arr):
                    pass
                else:
                    self.ui.alter_hint_lable.setText("请输入准确行号")
                    return 0 
            else:
                self.ui.alter_hint_lable.setText("请输入数字")
                return 0
        else:
            self.ui.alter_hint_lable.setText("请输入行号") 
            return 0 



        str2 = str2.replace("_",'')                                                 #将_去掉
        str2 = str2.replace(" ",'')
        if len(str2) != 0:                                                          #不为空
            if str2.encode('UTF-8').isalpha():                                        #如果为拼音
                pass
            else:
                self.ui.alter_hint_lable.setText("请输入拼音")
                return 0 

        if len(str3) != 0:                                                          #不为空
            if str3.isdigit():                                                      #如果为数字
                pass
            else:
                self.ui.alter_hint_lable.setText("请输入数字")
                return 0 
        
        if len(str4) != 0:                                                          #不为空
            if self.check_contain_chinese(str4):                                    #如果为中文
                pass
            else:
                self.ui.alter_hint_lable.setText("请输入中文")
                return 0
        
        arr = [str2,str3,str4]
        if len(str1) != 0:
            food_info_utils.alter_arr_food_info_csv(num-1,arr)
        arr,row = food_info_utils.get_food_info()                   #获取tab2表格数据
        self.ui.refresh_row(arr,row)                                #表格刷新
        self.arr = np.array(arr)                                    #更新存放在内存的数组
        self.ui.alter_hint_lable.setText("修改成功")
        self.price_info,self.names_info = food_info_utils.get_price_info()      # 更新信息，让检测时，信息即使改变
        

        
        


        
        
if __name__ == '__main__':
    app =  QtWidgets.QApplication(sys.argv)
    current_ui =Ui_Logic_Window()                   #实例化Ui_MainWindow
    current_ui.layout_main.show()                               #调用ui的show()以显示。同样show()是源于父类QtWidgets.QWidget的
    sys.exit(app.exec_())
    input("please input any key to exit!")

